package ui.excute;

import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import session.Session;
import ui.MainFrame;
import ui.result.QueryResultDialog;
import session.Session;  // 添加 Session 类的导入


import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;  // 添加 Session 类的导入

import session.Session;
import ui.MainFrame;

public class SQLExecutorHandler {
    private final JTabbedPane sqlTabbedPane;
    private final List<RSyntaxTextArea> sqlEditors;
    private final JTextArea consoleArea;

    public SQLExecutorHandler(JTabbedPane sqlTabbedPane, List<RSyntaxTextArea> sqlEditors, JTextArea consoleArea) {
        this.sqlTabbedPane = sqlTabbedPane;
        this.sqlEditors = sqlEditors;
        this.consoleArea = consoleArea;
    }

    public void executeSQL() {
        int index = sqlTabbedPane.getSelectedIndex();
        if (index == -1 || index >= sqlEditors.size()) return;

        RSyntaxTextArea editor = sqlEditors.get(index);
        String command = editor.getText().trim();
        if (command.isEmpty()) return;

        consoleArea.append("\n> " + command + "\n");
        executeCommand(command, false);
    }

    public void executeAndCommit() {
        int index = sqlTabbedPane.getSelectedIndex();
        if (index == -1 || index >= sqlEditors.size()) return;

        RSyntaxTextArea editor = sqlEditors.get(index);
        String command = editor.getText().trim();
        if (command.isEmpty()) return;

        consoleArea.append("\n> " + command + "\n");
        executeCommand(command, true);
    }

    public void executeSelectedSQL() {
        int index = sqlTabbedPane.getSelectedIndex();
        if (index == -1 || index >= sqlEditors.size()) return;

        RSyntaxTextArea editor = sqlEditors.get(index);
        String selectedText = editor.getSelectedText();

        if (selectedText != null && !selectedText.trim().isEmpty()) {
            consoleArea.append("\n> " + selectedText.trim() + "\n");
            executeCommand(selectedText, false);
        } else {
            executeSQL();
        }
    }

    private String getFirstKeyword(String sql) {
        // 移除注释
        sql = sql.replaceAll("--.*", "")
                .replaceAll("/\\*.*?\\*/", "");

        // 按分号分割语句，获取最后一个语句
        String[] statements = sql.split(";");
        String lastStatement = statements[statements.length - 1].trim();

        // 按空格/换行分割
        String[] tokens = lastStatement.split("\\s+");

        // 返回第一个非空token的大写形式
        for (String token : tokens) {
            if (!token.isEmpty()) {
                return token.toUpperCase();
            }
        }
        return "";
    }

    private void executeCommand(String command, boolean autoCommit) {
        try {
            Session session = Session.getCurrentSession();
            if (session == null) {
                consoleArea.append("请先登录\n");
                return;
            }

            long startTime = System.currentTimeMillis();

            // 分割复合语句
            String[] statements = command.split(";");
            String lastResult = "";

            for (String stmt : statements) {
                stmt = stmt.trim();
                if (stmt.isEmpty()) continue;

                // 检查是否为系统命令
                String commandType = getFirstKeyword(stmt).toLowerCase();
                if (UICommandProcessor.SYSTEM_COMMANDS.contains(commandType)) {
                    lastResult = UICommandProcessor.processSystemCommand(commandType, stmt);
                    consoleArea.append(lastResult + "\n");
                    continue;
                }

                // 执行SQL语句
                lastResult = processSQLCommand(session, stmt);
                consoleArea.append(lastResult + "\n");

                // 如果是SELECT查询，显示表格
                if (MainFrame.instance != null && getFirstKeyword(stmt).equals("SELECT")) {
                    MainFrame.instance.showQueryResultFromString(stmt, lastResult);
                }
            }

            long endTime = System.currentTimeMillis();
            consoleArea.append("执行时间: " + (endTime - startTime) + "ms\n");
            consoleArea.setCaretPosition(consoleArea.getDocument().getLength());
            consoleArea.update(consoleArea.getGraphics());

            // 刷新数据库树和表结构显示
            if (MainFrame.instance != null && MainFrame.instance.dbTreePanel != null) {
                MainFrame.instance.dbTreePanel.refreshTree();
            }

            if (autoCommit) {
                processSQLCommand(session, "commit");
                consoleArea.append("已自动提交事务\n");
                consoleArea.setCaretPosition(consoleArea.getDocument().getLength());
                consoleArea.update(consoleArea.getGraphics());
            }
        } catch (Exception e) {
            consoleArea.append("执行出错: " + e.getMessage() + "\n");
            consoleArea.setCaretPosition(consoleArea.getDocument().getLength());
            consoleArea.update(consoleArea.getGraphics());
            e.printStackTrace();
        }
    }

    private String processSQLCommand(Session session, String command) {
        command = command.trim();
        if (command.isEmpty()) return "";

        // 特殊处理删除数据库命令
        if (command.toLowerCase().startsWith("delete_db")) {
            String[] parts = command.split("\\s+");
            if (parts.length >= 2) {
                String dbName = parts[1];
                int result = session.deleteDatabase(dbName);
                return result == 1 ? "✅ 数据库删除成功" : "❌ 数据库删除失败";
            }
            return "❌ 无效的删除数据库命令格式";
        }

        if (command.toLowerCase().startsWith("select")) {
            ArrayList<ArrayList<String>> results = session.executeQuery(command);
            return formatQueryResults(results);
        } else {
            int affectedRows = session.executeUpdate(command);
            return "执行成功，影响行数: " + affectedRows;
        }
    }

    private String formatQueryResults(ArrayList<ArrayList<String>> results) {
        if (results == null || results.isEmpty()) return "查询无结果";

        StringBuilder sb = new StringBuilder("查询结果:\n");

        // 表头
        ArrayList<String> header = results.get(0);
        for (String col : header) {
            sb.append(col).append("\t");
        }
        sb.append("\n");

        // 数据行
        for (int i = 1; i < results.size(); i++) {
            ArrayList<String> row = results.get(i);
            for (String cell : row) {
                sb.append(cell).append("\t");
            }
            sb.append("\n");
        }

        return sb.toString();
    }
}